<script setup>
import {Delete, Edit} from '@element-plus/icons-vue'
import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {ref} from 'vue'
import {addArticleAPI, articleAPI, articleCategoryAPI, deleteArticleAPI, updateArticleAPI} from "../../api/article";
import {useTokenStore} from "../../store/token";
import {ElMessage} from "element-plus";

//表单校验
const form = ref(null)

//表单标题
const title = ref('')

//文章分类数据模型
const categorys = ref([])

//用户搜索时选中的分类id
const categoryId = ref('')

//用户搜索时选中的发布状态
const state = ref('')

//文章列表数据模型
const articles = ref([])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数

//抽屉的展示
const visibleDrawer = ref(false)

//添加表单数据模型
const articleData = ref({
  title: '',
  categoryId: '',
  coverImg: '',
  content: '',
  state: ''
})

//导入token
const tokenStore = useTokenStore();

//表单数据的校验
const rules = {
  title: [
    {required: true, message: '请输入文章标题', trigger: 'blur'},
  ],
  categoryId: [
    {required: true, message: '请选择文章分类', trigger: 'change'},
  ],
  coverImg: [
    {required: true, message: '请上传图片', trigger: 'blur'},
  ],
  content: [
    {required: true, message: '请输入文章内容', trigger: 'blur'},
  ]
}

// 回显文章分类
const getArticleCategorys = async () => {
  const result = await articleCategoryAPI();
  categorys.value = result.data;
};

// 加载文章列表
const getArticles = async () => {
  // 准备请求参数
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: categoryId.value ? categoryId.value : null,
    state: state.value ? state.value : null
  }

  // 发起请求
  const result = await articleAPI(params);
  // 渲染列表和总条数
  articles.value = result.data.items
  total.value = result.data.total
  // 将文章分类的id转换为name
  for (let i = 0; i < articles.value.length; i++) {
    const article = articles.value[i];
    for (let j = 0; j < categorys.value.length; j++) {
      const category = categorys.value[j];
      if (article.categoryId === category.id) {
        article.categoryName = category.categoryName
      }
    }
  }
}

//重置
const reset = () => {
  categoryId.value = ''
  state.value = ''
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  getArticles()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  getArticles()
}

// 清除表单数据
const clearArticleData = () => {
  articleData.value = {
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: ''
  }
}

// 文件上传成功的回调函数
const uploadSuccess = (result) => {
  // 渲染图片
  articleData.value.coverImg = result.data
  // 提示信息
  ElMessage.success(result.message ? result.message : '图片上传成功')
}

// 添加文章
const addArticle = (state) => {
  // 开始校验
  form.value.validate(async valid => {
    if (valid) {
      // 赋值
      articleData.value.state = state
      // 发送发布文章请求
      const result = await addArticleAPI(articleData.value);
      // 提示信息
      ElMessage.success(result.message ? result.message : '文章发布成功')
      // 隐藏抽屉
      visibleDrawer.value = false
      // 刷新
      getArticles()
    }
  })
}

// 编辑按钮的数据回显
const edit = (row) => {
  // 修改表单标题为修改文章
  title.value = '修改文章'
  articleData.value = row
  // 显示抽屉
  visibleDrawer.value = true
}

// 修改文章
const updateArticle = (state) => {
  // 开始校验
  form.value.validate(async valid => {
    if (valid) {
      // 赋值
      articleData.value.state = state
      // 发送修改文章请求
      const result = await updateArticleAPI(articleData.value);
      // 提示信息
      ElMessage.success(result.message ? result.message : '文章修改成功')
      // 隐藏抽屉
      visibleDrawer.value = false
      // 刷新
      getArticles()
    }
  })
}

// 删除文章
const deleteArticle = async (row) => {
  const result = await deleteArticleAPI(row.id);
  // 提示信息
  ElMessage.success(result.message ? result.message : '文章删除成功')
  // 刷新
  getArticles()
}

// 执行函数
getArticleCategorys()
getArticles()

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文章管理</span>
        <div class="extra">
          <el-button type="primary" @click="title='添加文章';visibleDrawer=true;clearArticleData()">添加文章</el-button>
        </div>
      </div>
    </template>

    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
      <!-- 添加文章表单 -->
      <el-form ref="form" :model="articleData" label-width="100px" :rules="rules">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleData.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryId">
          <el-select placeholder="请选择" v-model="articleData.categoryId">
            <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="coverImg">

          <!--
                auto-upload：设置是否自动上传
                action：设置服务器接口地址
                name：设置上传的文件字段名
                headers：设置上传的请求头
                on-success：设置上传成功的回调函数
               -->
          <el-upload class="avatar-uploader"
                     :show-file-list="false"
                     :auto-upload="true"
                     action="/api/upload"
                     name="file"
                     :headers="{'Authorization':tokenStore.token}"
                     :on-success="uploadSuccess">
            <img v-if="articleData.coverImg" :src="articleData.coverImg" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor">
            <!--     富文本编辑器       -->
            <quill-editor
                theme="snow"
                v-model:content="articleData.content"
                contentType="html"
            >
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="title==='添加文章'?addArticle('已发布'):updateArticle('已发布')">发布</el-button>
          <el-button type="info" @click="title==='添加文章'?addArticle('草稿'):updateArticle('已发布')">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="文章分类：">
        <el-select placeholder="请选择" v-model="categoryId">
          <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.categoryName"
              :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getArticles">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime"></el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="edit(row)"></el-button>
          <el-popconfirm title="你确认删除该文章吗？" confirm-button-text="确认" cancel-button-text="取消"
                         @confirm="deleteArticle(row)">
            <template #reference>
              <el-button :icon="Delete" circle plain type="danger"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5,10,15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>
</template>


<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>